<template>
  <div>
    <!-- 头部 -->
    <el-row>
      <el-col :span="12">
        <div class="title">文件信息：</div>
      </el-col>
      <el-col :span="12">
        <div class="my_button">
          <!-- 添加展开按钮，点击时触发 toggleShowAll 函数 -->
          <el-button type="success" size="small" icon="el-icon-sort"
                     @click="toggleShowAll">{{ showAll ? '收起' : '展开' }}
          </el-button>
          <el-button type="primary" size="small" icon="el-icon-edit"
                     @click="editing">编辑
          </el-button>
        </div>
      </el-col>
    </el-row>

    <!-- 文件信息表单 -->
    <template v-if="fileInfo && Object.keys(fileInfo).length > 0">
      <el-form :label-position="'right'" label-width="160px" :model="fileList">
        <el-row :gutter="10" style="margin-top: 20px">
          <el-col v-for="comment in visibleCommentList" :key="comment.columnname" :span="12" class="form-col"
                  v-if="comment.columncomment !== ''">
            <el-form-item :label="comment.columncomment + '：'">
              <div class="table-content">{{ fileList[comment.columnname] }}</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
    <template v-else>
      <el-empty description="无文件信息"></el-empty>
    </template>

    <!-- 编辑弹窗 -->
    <el-dialog title="文件信息编辑：" :visible.sync="dialogVisible" width="50%" center>
      <div class="dialog-content">
        <el-form :model="tempFileList">
          <el-row>
            <el-col v-for="comment in tempCommentList" :key="comment.columnname" :span="12"
                    v-if="comment.columncomment !== ''">
              <el-form-item :label="comment.columncomment + '：'">
                <el-input class="custom-input" v-model="tempFileList[comment.columnname]"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetDialogData">恢复</el-button>
        <el-button type="primary" @click="saveDialogData">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getFileCommentInfo, updateFileInfo} from "@/api/system/fileinfo";

export default {
  props: {
    fileInfo: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      fileList: {},
      showAll: false, // 是否显示全部文件信息
      visibleCommentList: {}, // 可见的文件字段
      // 默认可见的文件字段
      defaultCommentList: ['文件题名', '责任者', '文件时间', '页数', '载体类型',
        '密级', '保存期限', '文件编号', '编制单位', '纸张类型', '主题词'],
      tempFileList: {}, // 编辑弹窗中临时保存的数据
      tempCommentList: {}, // 编辑弹窗中可编辑字段
      fileCommentList: null,
      isEditing: false, // 是否处于编辑状态
      dialogVisible: false, // 编辑弹窗是否可见
    };
  },
  watch: {
    fileInfo: {
      immediate: true, // 在组件创建时立即执行一次
      handler(newVal) {
        this.fileList = {...newVal}; // 使用对象的深拷贝方式赋值
        this.tempFileList = {...newVal}; // 初始化编辑弹窗中的临时数据
      }
    }
  },
  created() {
    this.getFileComment().then(() => {
      this.transferComment();
    });
  },
  methods: {
    //转换可见的属性
    transferComment() {
      if (this.showAll) {
        this.visibleCommentList = this.fileCommentList.filter((comment) => comment.columncomment !== "");
      } else {
        const nonEmptyComments = this.fileCommentList.filter((comment) => comment.columncomment !== "");
        this.visibleCommentList = [];
        for (let i = 0; i < nonEmptyComments.length; i++) {
          if (this.defaultCommentList.includes(nonEmptyComments[i].columncomment)) {
            this.visibleCommentList.push(nonEmptyComments[i]);
          }
        }
      }
    },
    // 切换展开按钮的状态，显示全部案卷信息或部分案卷信息
    toggleShowAll() {
      this.showAll = !this.showAll;
      this.transferComment();
    },
    // 下划线转驼峰命名
    underscoreToCamel(str) {
      return str.replace(/_([a-z])/g, (match, letter) => letter.toUpperCase());
    },
    //获取文件字段信息和注释
    getFileComment() {
      return getFileCommentInfo()
        .then(res => {
          // this.fileCommentList = res;
          this.fileCommentList = res.map(comment => ({
            columncomment: comment.columncomment,
            columnname: this.underscoreToCamel(comment.columnname), // 转换属性名
          }));
        })
        .catch(error => {
          this.$message.error('获取文件信息注释失败：' + error);
        });
    },
    editing() {
      const nonEmptyComments = this.fileCommentList.filter((comment) => comment.columncomment !== "");
      this.tempCommentList = [];
      for (let i = 0; i < nonEmptyComments.length; i++) {
        if (this.defaultCommentList.includes(nonEmptyComments[i].columncomment)) {
          this.tempCommentList.push(nonEmptyComments[i]);
        }
      }
      this.isEditing = true;
      this.dialogVisible = true;
    },
    resetDialogData() {
      this.tempFileList = {...this.fileList};
    },
    saveDialogData() {
      this.$confirm('确认修改吗？', '提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        this.isEditing = false;
        // 调用 updateFileInfo 方法，并传入 tempFileList 数据
        updateFileInfo(this.tempFileList)
          .then(() => {
            this.$message.success('保存成功！');
            // 如果保存成功，将 tempFileList 的数据同步到 fileList
            this.$emit('updateFileInfo');
            this.fileList = {...this.tempFileList};
            this.dialogVisible = false;
          })
          .catch(error => {
            this.$message.error('保存失败：' + error);
            this.dialogVisible = false;
          });
      }).catch(() => {
        // 取消保存
        this.$message.info('已取消保存');
      });
    },
  }
};
</script>

<style>
.title {
  margin-left: 2%;
  margin-top: 10px;
  font-size: 20px;
  font-weight: bold;
  color: rgb(26, 115, 198);
}

.dialog-content {
  max-height: 500px; /* 设置最大高度，内容区域超出时会出现滚动条 */
  overflow-y: auto; /* 内容区域出现滚动条 */
}

.dialog-footer {
  position: sticky;
  bottom: 0;
  padding: 10px;
}

.custom-input {
  width: 98%; /* 设置输入框的宽度，根据实际情况调整 */
}

.my_button {
  display: flex;
  align-items: center;
  margin-right: 2%;
  margin-top: 12px;
}
</style>

